package com.healthdata.controller;

import com.healthdata.entity.UserApplication;
import com.healthdata.service.UserService;
import com.healthdata.util.JwtUtil;
import com.healthdata.vo.UserApplicationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/researcher")
@PreAuthorize("hasAuthority('RESEARCHER')")
public class ResearcherController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    // 提交申请
    @PostMapping("/sendApplication")
    public Map<String, Object> applyForAuditor(@RequestBody Map<String, String> applyInfo, @RequestHeader("Authorization") String token) {
        Map<String, Object> result = new HashMap<>();
        Long userId = jwtUtil.getUserIdFromToken(token);
        if (userId != null) {
            String reason = applyInfo.get("reason");
            String targetRole = applyInfo.get("targetRole"); // 获取前端传递的 targetRole

            if (targetRole == null || (!"AUDITOR".equals(targetRole) && !"ADMIN".equals(targetRole))) {
                result.put("success", false);
                result.put("message", "目标角色必须为 AUDITOR 或 ADMIN");
                return result;
            }

            UserApplication application = new UserApplication();
            application.setUserId(userId);
            application.setReason(reason);
            application.setStatus("未处理");
            application.setTargetRole(targetRole); // 直接使用前端传递的 targetRole

            boolean success = userService.submitApplication(application);
            result.put("success", success);
            result.put("message", success ? "申请提交成功" : "申请提交失败");
        } else {
            result.put("success", false);
            result.put("message", "Token 无效");
        }
        return result;
    }

    // 查看申请进度
    @GetMapping("/checkApplicationStatus")
    public Map<String, Object> checkApplicationStatus(@RequestHeader("Authorization") String token) {
        Map<String, Object> result = new HashMap<>();
        Long userId = jwtUtil.getUserIdFromToken(token);
        if (userId != null) {
            List<UserApplicationVO> applicationVOs = userService.getUserApplication(userId);
            if (!applicationVOs.isEmpty()) {
                result.put("success", true);
                result.put("applications", applicationVOs);
            } else {
                result.put("success", true);
                result.put("message", "没有申请信息");
            }
        } else {
            result.put("success", false);
            result.put("message", "Token 无效");
        }
        return result;
    }
}
